const db = require('../db/index')
    //引入加密包
const bcryt = require('bcryptjs')
exports.getUsers = (req, res) => {
        // res.ResData("获取用户数据")
        //接收数据  get请求数据 用req.query  如果是post请求 req.body
        // console.log(req.query);
        const keyword = req.query.query;
        const page_size = req.query.pagesize; //每页显示条数
        const page_num = req.query.pagenum; //当前页码数
        if (page_size == '' || page_num == '')
            res.ResData("参数错误")
            // var sql = `select * from sp_manager,sp_role where sp_manager.role_id=sp_role.role_id limit ?,?`
        var sql = `select * from sp_manager a left join sp_role b on a.role_id=b.role_id `
        if (keyword) {
            sql += "where a.mg_name like '%" + keyword + "%' limit ?,?"
        } else {
            sql += "limit ?,?"
        }
        var params = [(parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size)];
        db.query(sql, params, (err, result) => {
            if (err) return res.ResData("查询失败");
            // res.ResData("获取用户列表成功",200,result)
            //计算总记录数

            var sqlTotal = "select count(*) as num from sp_manager ";
            if (keyword) {
                sqlTotal += "where mg_name like '%" + keyword + "%'";
            }
            db.query(sqlTotal, (err, among) => {
                if (err) return res.ResData(err)
                var total = among[0]['num']; //总记录数
                if (page_num > Math.ceil(total / page_size)) {
                    return res.ResData("已经超过最大页")

                }
                // res.ResData("获取用户列表成功", 200, total)
                //组合返回数据
                var retUsers = []
                for (idx in result) {
                    var manager = result[idx];
                    var role_name = manager.role_name;
                    if (!manager.role_id) {
                        role_name = "超级管理员"
                    }
                    retUsers.push({
                        "id": manager.mg_id,
                        "username": manager.mg_name,
                        "mobile": manager.mg_mobile,
                        "email": manager.mg_email,
                        "create_time": manager.mg_time,
                        "mg_state": manager.mg_state == 1, // 当前用户的状态
                        "role_name": role_name
                    })
                }
                const data = {
                    "totalpage": total,
                    "pagenum": page_num,
                    "users": retUsers,
                }
                res.ResData("获取用户列表成功", 200, data)
            })
        })
    }
    //添加用户
exports.addUsers = (req, res) => {

        // res.ResData("添加用户")
        //1.获取用户数据
        // console.log(req.body);
        var mg_name = req.body.username
            //头部引入加密包
        var mg_pwd = bcryt.hashSync(req.body.password);
        var mg_email = req.body.email;
        var mg_mobile = req.body.mobile
        var mg_time = (Date.parse(new Date()) / 1000)
            //2.检查用户是否存在
        var sql = "select * from sp_manager where mg_name= ?"
        db.query(sql, mg_name, (err, result) => {
            if (err) return res.ResData("添加失败")
            if (result.length > 0)
                return res.ResData("用户名已经存在")
                    //3.添加数据
            var sql = "insert into sp_manager (mg_name,mg_pwd,mg_time,mg_mobile,mg_email,mg_state) values (?,?,?,?,?,?)";

            db.query(sql, [mg_name, mg_pwd, mg_time, mg_mobile, mg_email, 0], (err, data) => {
                if (err) return res.ResData("添加失败");
                res.ResData("添加用户成功", 200, {
                    "username": mg_name,
                    "mobile": mg_mobile,
                    "email": mg_email,
                    "create_time": mg_time
                })
            })

            //4.返回结果
        })

    }
    //修改用户状态
exports.changeState = (req, res) => {
        // res.ResData("修改用户状态")
        // console.log(req.params);
        //获取用户数据
        var id = req.params.uId;
        var mg_state = req.params.type;
        if (mg_state === 'true') mg_state = 1
        else mg_state = 0;
        //更新状态
        var sql = "update sp_manager set mg_state=? where mg_id=?"
        db.query(sql, [mg_state, id], (err, result) => {
            // console.log(result);
            if (err) return res.ResData("修改用户状态失败")
            if (result.affectedRows > 0) {
                res.ResData("更新状态成功", 200)

            }
        })
    }
    //根据Id查询用户信息
exports.search = (req, res) => {
    // res.ResData("查询用户")

    //1、接收参数
    var id = req.params.id;
    //2、查询用户信息
    var sql = "select * from sp_manager where mg_id=?"
        //3、返回结果
    db.query(sql, id, (err, result) => {
        if (err) return res.ResData("查询用户失败");
        if (result.length > 0) {
            res.ResData("查询用户成功", 200, {
                "id": result[0].mg_id,
                "username": result[0].mg_name,
                "role_id": result[0].role_id,
                "mobile": result[0].mg_mobile,
                "email": result[0].mg_email,


            })

        } else {
            res.ResData("用户查询失败")
        }

    })




}
exports.edit = (req, res) => {
    //编辑用户提交
    // res.ResData("编辑用户提交")
    //1、接收参数
    var id = req.params.id;
    var mobile = req.body.mobile;
    var email = req.body.email;

    // //2、更新数据
    var sql = "update sp_manager set mg_mobile=?, mg_email=? where mg_id=?"
        //     // console.log(sql);
    db.query(sql, [mobile, email, id], (err, result) => {
            if (err) return res.ResData("更新用户信息失败")
                // console.log(result);
                // if(result.length>0)
            if (result.affectedRows < 1)
                return res.ResData("更新用户信息失败");
            var sql = "select * from sp_manager where mg_id=?"
            db.query(sql, id, (err, resResult) => {
                res.ResData("更新用户信息成功", 200, {
                    "id": resResult[0].mg_id,
                    "username": resResult[0].mg_name,
                    "role_id": resResult[0].role_id,
                    "mobile": resResult[0].mg_mobile,
                    "email": resResult[0].mg_email
                })
            })

        })
        //     //3、返回结果
}
exports.delete = (req, res) => {
    var id = req.params.id;
    var sql = "delete from sp_manager where mg_id=?"
    db.query(sql, id, (err, result) => {
        if (err) return res.ResData("删除失败")
        if (result.affectedRows != 1) return res.ResData("删除失败");
        res.ResData("删除成功", 200)
    })
}
exports.role = (req, res) => {
    // res.ResData("分配角色成功")
    //获取用户数据
    var id = req.params.id;
    var rid = req.body.rid;
    var sql = "update sp_manager set role_id=? where mg_id=?"
    db.query(sql, [rid, id], (err, result) => {
        if (err) return res.ResData("设置角色失败")
        if (result.affectedRows != 1) return res.ResData("设置角色失败")
        var sql = "select * from sp_manager where mg_id=?"
        db.query(sql, id, (err, data) => {
            res.ResData("设置角色成功", 200, {
                "id": data[0].mg_id,
                "username": data[0].mg_name,
                "rid": data[0].role_id,
                "mobile": data[0].mg_mobile,
                "email": data[0].mg_email,
            })
        })
    })
}